import { createRouter, createWebHistory } from 'vue-router'

// 导入页面组件
const Login = () => import('../views/Login.vue')
const Register = () => import('../views/Register.vue')
const Order = () => import('../views/Order.vue')

// 路由配置
const routes = [
  {
    path: '/',
    redirect: '/login' // 默认重定向到登录页面
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/register',
    name: 'Register',
    component: Register
  },
  {
    path: '/order',
    name: 'Order',
    component: Order,
    meta: {
      requiresAuth: true // 需要登录才能访问
    }
  }
]

// 创建路由实例
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})

// 路由守卫，检查登录状态
router.beforeEach((to, from, next) => {
  // 检查路由是否需要登录
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // 检查是否已登录 - 检查token或user是否存在
    const token = localStorage.getItem('token')
    const user = localStorage.getItem('user')
    
    if (!token || !user) {
      // 未登录，重定向到登录页面
      next({ name: 'Login' })
    } else {
      // 已登录，正常访问
      next()
    }
  } else {
    // 不需要登录的路由，直接访问
    next()
  }
})

export default router